package com.banshuibao.bsb_android.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.CalendarAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.CalenderFormModel;
import com.banshuibao.bsb_android.util.CalendarString;
import com.banshuibao.bsb_android.view.CustomDayView;

import com.google.gson.Gson;
import com.ldf.calendar.component.CalendarAttr;
import com.ldf.calendar.component.CalendarViewAdapter;
import com.ldf.calendar.interf.OnSelectDateListener;
import com.ldf.calendar.model.CalendarDate;
import com.ldf.calendar.view.Calendar;
import com.ldf.calendar.view.MonthPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zyh on 2018/5/18.
 */

public class CalendarActivity extends BaseActivity {

    private MonthPager monthPager;
    private ArrayList<Calendar> currentCalendars = new ArrayList<>();
    private CalendarViewAdapter calendarAdapter;
    private OnSelectDateListener onSelectDateListener;
    private int mCurrentPage = MonthPager.CURRENT_DAY_INDEX;
    private CalendarDate currentDate;
    private boolean initiated = false;
    private RecyclerView recyclerView;
    private CalendarAdapter calendarDateAdapter;
    private ImageView pre, next;
    private TextView day_Text;
    private CalendarString calendarString;
    private int[] colors = {R.drawable.icon_calendar_sign_red, R.drawable.icon_calendar_sign_blue
            , R.drawable.icon_calendar_sign_orange, R.drawable.icon_calendar_sign_yellow,
            R.drawable.icon_calendar_sign_green};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);
        context = this;
        monthPager = findViewById(R.id.calendar_view);

        initView();
        initCurrentDate();
        initCalendarView();
        initRecyclerView();
    }

    private void initView() {
        setTitleText("办税日历");
        day_Text = findViewById(R.id.day_text);
        day_Text.getPaint().setFakeBoldText(true);
        pre = findViewById(R.id.pre);
        next = findViewById(R.id.next);
        pre.setOnClickListener(l);
        next.setOnClickListener(l);
    }

    private View.OnClickListener l = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.pre:
                    monthPager.setCurrentItem(monthPager.getCurrentPosition() - 1, true);
                    break;
                case R.id.next:
                    monthPager.setCurrentItem(monthPager.getCurrentPosition() + 1, true);
                    break;
            }
        }
    };

    /**
     * onWindowFocusChanged回调时，将当前月的种子日期修改为今天
     *
     * @return void
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !initiated) {
            refreshMonthPager();
            initiated = true;
        }
    }


    /**
     * 初始化currentDate
     *
     * @return void
     */
    private void initCurrentDate() {
        currentDate = new CalendarDate();
        day_Text.setText(String.valueOf(currentDate.getYear() + "年" + currentDate.getMonth() + "月"));
    }

    /**
     * 初始化CustomDayView，并作为CalendarViewAdapter的参数传入
     */
    private void initCalendarView() {
        initListener();
        CustomDayView customDayView = new CustomDayView(context, R.layout.item_custom_day_view);
        calendarAdapter = new CalendarViewAdapter(
                context,
                onSelectDateListener,
                CalendarAttr.CalendarType.MONTH,
                CalendarAttr.WeekArrayType.Monday,
                customDayView);
        calendarAdapter.setOnCalendarTypeChangedListener(new CalendarViewAdapter.OnCalendarTypeChanged() {
            @Override
            public void onCalendarTypeChanged(CalendarAttr.CalendarType type) {
                recyclerView.scrollToPosition(0);
            }
        });
        initMonthPager();
    }

    private void initRecyclerView() {
        recyclerView = findViewById(R.id.list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setNestedScrollingEnabled(false);
        calendarDateAdapter = new CalendarAdapter(this);
        recyclerView.setAdapter(calendarDateAdapter);
        calendarString = new CalendarString();
        getForm(currentDate.getMonth(), mCurrentPage);
    }

    private void getForm(int time, final int position) {
        if (position != mCurrentPage) {
            return;
        }
        time *= currentDate.getYear();
        String json = "";
        switch (time) {
            case 2018:
                json = calendarString.getJanuary();
                break;
            case 2018 * 2:
                json = calendarString.getFebruary();
                break;
            case 2018 * 3:
                json = calendarString.getMarch();
                break;
            case 2018 * 4:
                json = calendarString.getApril();
                break;
            case 2018 * 5:
                json = calendarString.getMay();
                break;
            case 2018 * 6:
                json = calendarString.getJune();
                break;
            case 2018 * 7:
                json = calendarString.getJuly();
                break;
            case 2018 * 8:
                json = calendarString.getAugust();
                break;
            case 2018 * 9:
                json = calendarString.getSeptember();
                break;
            case 2018 * 10:
                json = calendarString.getOctober();
                break;
            case 2018 * 11:
                json = calendarString.getNovember();
                break;
            case 2018 * 12:
                json = calendarString.getDecember();
                break;
        }
        if (TextUtils.isEmpty(json)) {
            List<CalenderFormModel.Rls> rls = new ArrayList<>();
            if (calendarDateAdapter != null)
                calendarDateAdapter.setList(rls);
            if (calendarAdapter != null)
                initMarkData(rls);
            return;
        }
        Gson gson = new Gson();
        CalenderFormModel model = gson.fromJson(json, CalenderFormModel.class);
        CalenderFormModel.Data data = model.getJson();
        List<CalenderFormModel.Rls> datas = data.getList();
        List<CalenderFormModel.Rls> rls = new ArrayList<>();
        int size = datas.size();
        for (int i = 0; i < size; ++i) {
            if (datas.get(i) != null) {
                CalenderFormModel.Rls rls1 = datas.get(i);
                String start = rls1.getBskssj();
                String end = rls1.getBsjssj();
                int size1 = rls.size();
                if (size1 >= colors.length) {
                    size1 = 0;
                }
                rls1.setColor(colors[size1]);
                rls.add(rls1);
                for (int j = i + 1; j < size; ++j) {
                    if (datas.get(j) != null) {
                        CalenderFormModel.Rls rls2 = datas.get(j);
                        String start1 = rls2.getBskssj();
                        String end1 = rls2.getBsjssj();
                        if (TextUtils.equals(start1, start) && TextUtils.equals(end, end1)) {
                            rls2.setBskssj("");
                            rls2.setBsjssj("");
                            rls.add(rls2);
                            datas.set(j, null);
                        }
                    }
                }
            }
        }
        if (calendarDateAdapter != null)
            calendarDateAdapter.setList(rls);
        if (calendarAdapter != null)
            initMarkData(rls);
    }

    /**
     * 初始化标记数据，HashMap的形式，可自定义
     * 如果存在异步的话，在使用setMarkData之后调用 calendarAdapter.notifyDataChanged();
     */
    private void initMarkData(List<CalenderFormModel.Rls> list) {
        HashMap<String, String> markData = new HashMap<>();
        int size = list.size();
        for (int i = 0; i < size; ++i) {
            CalenderFormModel.Rls rls = list.get(i);
            if (!TextUtils.isEmpty(rls.getBskssj()) && !TextUtils.isEmpty(rls.getBsjssj())) {
                if (markData.get(formatDate(rls.getBskssj())) != null) {
                    String mark = markData.get(formatDate(rls.getBskssj()));
                    String[] strs = mark.split("_");
                    String colors = strs[1];
                    int number = Integer.valueOf(strs[0]) + 1;
                    String value = number + "_" + colors + "," + rls.getColor();
                    markData.put(formatDate(rls.getBskssj()), value);
                } else {
                    String value = 1 + "_" + rls.getColor();
                    markData.put(formatDate(rls.getBskssj()), value);
                }
                if (markData.get(formatDate(rls.getBsjssj())) != null) {
                    String mark = markData.get(formatDate(rls.getBsjssj()));
                    String[] strs = mark.split("_");
                    String colors = strs[1];
                    int number = Integer.valueOf(strs[0]) + 1;
                    String value = number + "_" + colors + "," + rls.getColor();
                    markData.put(formatDate(rls.getBsjssj()), value);
                } else {
                    String value = 1 + "_" + rls.getColor();
                    markData.put(formatDate(rls.getBsjssj()), value);
                }
            }
        }
        calendarAdapter.setMarkData(markData);
    }

    private String formatDate(String str) {
        int year = Integer.valueOf(str.substring(0, 4));
        int month = Integer.valueOf(str.substring(5, 7));
        int day = Integer.valueOf(str.substring(8, 10));
        return year + "-" + month + "-" + day;
    }

    private void initListener() {
        onSelectDateListener = new OnSelectDateListener() {
            @Override
            public void onSelectDate(CalendarDate date) {
                refreshClickDate(date);
            }

            @Override
            public void onSelectOtherMonth(int offset) {
                //偏移量 -1表示刷新成上一个月数据 ， 1表示刷新成下一个月数据
                monthPager.selectOtherMonth(offset);
            }
        };
    }


    private void refreshClickDate(CalendarDate date) {
        currentDate = date;
    }

    /**
     * 初始化monthPager，MonthPager继承自ViewPager
     *
     * @return void
     */
    private void initMonthPager() {
        monthPager.setAdapter(calendarAdapter);
        monthPager.setCurrentItem(MonthPager.CURRENT_DAY_INDEX);
        monthPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                position = (float) Math.sqrt(1 - Math.abs(position));
                page.setAlpha(position);
            }
        });
        monthPager.addOnPageChangeListener(new MonthPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPage = position;
                currentCalendars = calendarAdapter.getPagers();
                if (currentCalendars.get(position % currentCalendars.size()) != null) {
                    CalendarDate date = currentCalendars.get(position % currentCalendars.size()).getSeedDate();
                    currentDate = date;
                    day_Text.setText(String.valueOf(currentDate.getYear() + "年" + currentDate.getMonth() + "月"));
                    getForm(currentDate.getMonth(), mCurrentPage);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void refreshMonthPager() {
        CalendarDate today = new CalendarDate();
        calendarAdapter.notifyDataChanged(today);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (currentCalendars != null) {
            currentCalendars.clear();
            currentCalendars = null;
        }
        if (calendarDateAdapter != null) {
            calendarDateAdapter.clear();
            calendarDateAdapter = null;
        }
        calendarAdapter = null;
    }
}
